package com.winz.cultureapp.activity;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import androidx.core.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.winz.cultureapp.R;
import com.winz.cultureapp.base.BaseAppCompatActivity;
import com.winz.cultureapp.http.DownloadUtils;
import com.winz.cultureapp.widge.SelSexDialog;
import com.winz.cultureapp.widge.TimerSelector;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 注册志愿者
 */
public class RegisterVolunteerActivity extends BaseAppCompatActivity implements TimerSelector.OkClickListener {
    private static final int BIRTH_TIME = 0x000001;
    private static final String PERMISSION_WRITE_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    private static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
    private static final int REQUEST_PERMISSION_CODE = 267;

    @BindView(R.id.tv_top_title)
    TextView mTv_top_title;
    @BindView(R.id.et_name)
    EditText mEt_name;
    @BindView(R.id.et_tell)
    EditText mEt_tell;
    @BindView(R.id.tv_sex)
    TextView mTv_sex;
    @BindView(R.id.tv_birth)
    TextView mTv_birth;
    @BindView(R.id.et_idcard)
    EditText mEt_idcard;
    @BindView(R.id.et_native)
    EditText mEt_native;
    @BindView(R.id.et_nation)
    EditText mEt_nation;
    @BindView(R.id.et_politics)
    EditText mEt_politice;
    @BindView(R.id.et_stature)
    EditText mEt_stature;
    @BindView(R.id.et_degree)
    EditText mEt_degree;
    @BindView(R.id.et_work)
    EditText mEt_work;
    @BindView(R.id.et_lauguages)
    EditText mEt_lauguages;
    @BindView(R.id.et_computer)
    EditText mEt_computer;
    @BindView(R.id.et_duty)
    EditText mEt_duty;
    @BindView(R.id.et_experience)
    EditText mEt_experience;
    @BindView(R.id.et_address)
    EditText mEt_address;
    @BindView(R.id.et_school)
    EditText mEt_school;
    @BindView(R.id.et_major)
    EditText mEt_major;
    @BindView(R.id.et_email)
    EditText mEt_email;
    @BindView(R.id.et_qq)
    EditText mEt_qq;
    @BindView(R.id.et_postcode)
    EditText mEt_postcode;
    @BindView(R.id.et_office)
    EditText mEt_office;


    private SelSexDialog mSel_sex;

    private String sex; // 当前选择性别记录
    private TimerSelector ts_birht;
    private String birthDate; // 当前选择的日期
    private long birth;

    private File file;
    private Uri mUriFromFile;
    private static final String FILE_PROVIDER_AUTHORITY = "com.winz.cultureapp.fileprovider";


    @Override
    protected int contentView() {
        return R.layout.activity_register_volunteer;
    }

    @Override
    protected void initViews() {
        mTv_top_title.setText(getString(R.string.register_volunteer_top_title));

        mSel_sex = new SelSexDialog(this);

        ts_birht = new TimerSelector(this, "yyyy年MM月dd日");
        ts_birht.setOkClickListener(this);
    }

    @Override
    protected void initEvents() {
        mSel_sex.setOkButtonOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSel_sex.dismiss();
                sex = mSel_sex.getSelSex();
                mTv_sex.setText(sex);
            }
        });
    }


    @OnClick({R.id.fl_back, R.id.ll_sex, R.id.ll_birth,R.id.ll_file, R.id.btn_submit})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.fl_back:
                finish();
                break;
            case R.id.ll_sex: // 选择性别
                mSel_sex.show();
                break;
            case R.id.ll_birth: // 选择出生
                ts_birht.show(mTv_birth, BIRTH_TIME);
                break;
            case R.id.ll_file:
                // 下载文件
                download();
                break;
            case R.id.btn_submit:
                if (isAllRight()) {
                    showMsg("提交");
                }
                break;
        }
    }


    /**
     * 时间选择器
     *
     * @param view
     * @param date
     * @param time
     * @param flag
     */
    @Override
    public void okClick(View view, String date, long time, int flag) {
        if (flag == BIRTH_TIME) {
            mTv_birth.setText(date);
            birthDate = date;
            birth = time;
        }
    }

    /**
     * 判断是否全部填写
     *
     * @return
     */
    private boolean isAllRight() {
        if (TextUtils.isEmpty(getEditTextStr(mEt_name))) {
            showMsg("请输入姓名");
            return false;
        }

        if (TextUtils.isEmpty(getEditTextStr(mEt_tell))) {
            showMsg("请输入手机号");
            return false;
        }

        if (TextUtils.isEmpty(getEditTextStr(mEt_idcard))) {
            showMsg("请输入身份证号码");
            return false;
        }

        if (TextUtils.isEmpty(mTv_sex.getText())) {
            showMsg("请选择性别");
            return false;
        }
        if (TextUtils.isEmpty(mTv_birth.getText())) {
            showMsg("请选择出年日期");
            return false;
        }

        if (TextUtils.isEmpty(getEditTextStr(mEt_native))) {
            showMsg("请输入籍贯");
            return false;
        }
        if (TextUtils.isEmpty(getEditTextStr(mEt_nation))) {
            showMsg("请输入民族");
            return false;
        }
        if (TextUtils.isEmpty(getEditTextStr(mEt_stature))) {
            showMsg("请输入身高");
            return false;
        }
        if (TextUtils.isEmpty(getEditTextStr(mEt_degree))) {
            showMsg("请输入文化程度");
            return false;
        }
        if (TextUtils.isEmpty(getEditTextStr(mEt_work))) {
            showMsg("请输入工作单位");
            return false;
        }
        if (TextUtils.isEmpty(getEditTextStr(mEt_lauguages))) {
            showMsg("请输入外语水平");
            return false;
        }
        if (TextUtils.isEmpty(getEditTextStr(mEt_computer))) {
            showMsg("请输入计算机水平");
            return false;
        }
        if (TextUtils.isEmpty(getEditTextStr(mEt_duty))) {
            showMsg("请输入职务");
            return false;
        }
        if (TextUtils.isEmpty(getEditTextStr(mEt_experience))) {
            showMsg("请输入有或者无");
            return false;
        }
        if (TextUtils.isEmpty(getEditTextStr(mEt_address))) {
            showMsg("请输入通讯电址");
            return false;
        }

        return true;
    }

    /**
     * 下载文件
     */
    private void download() {
        file = createPdfFile();//创建用来保存照片的文件
        mUriFromFile = Uri.fromFile(file);
        showProgressDialog("文件下载中,请稍候....");
        DownloadUtils.getInstance().download("http://zheli.org/data/i20190126110347.pdf", file, new DownloadUtils.OnFinishedListener() {
            @Override
            public void onFinished(String filePath) {
                dismissProgressDialog();
                galleryAddFile(mUriFromFile);
                Intent intent = new Intent("android.intent.action.VIEW");
                intent.addCategory("android.intent.category.DEFAULT");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                Uri uri = null;
                File file = new File(filePath);
                if (file.exists()) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        //data是file类型,忘了复制过来
                        uri = FileProvider.getUriForFile(context, FILE_PROVIDER_AUTHORITY, new File(filePath));

                    } else {
                        uri = Uri.fromFile(new File(filePath));
                    }
                }
                //pdf文件要被读取所以加入读取权限
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(uri, "application/pdf");
//              startActivity(intent);
                startActivity(Intent.createChooser(intent, "标题"));
            }

            @Override
            public void onFailed(String error) {
                dismissProgressDialog();
                showMsg("下载失败");
            }
        });

    }

    /**
     * 创建用来存储文件，以时间来命名就不会产生命名冲突
     *
     * @return 创建的文件
     */
    private File createPdfFile() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "volunteer_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File imageFile = null;
        try {
            imageFile = File.createTempFile(imageFileName, ".doc", storageDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageFile;
    }

    /**
     * 将下载到的文件添加系统文体列表
     *
     * @param uri
     */
    private void galleryAddFile(Uri uri) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);//ACTION_MEDIA_SCANNER_SCAN_FILE
        mediaScanIntent.setData(uri);
        sendBroadcast(mediaScanIntent);
    }

}
